package com.lpf.MyGameSaveBackup.GameSaveBackup.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lpf.MyGameSaveBackup.GameSaveBackup.service.GameSaveBackupService;
import com.lpf.MyGameSaveBackup.GameSaveBackup.vo.GameSaveBackVo;
import com.lpf.MyGameSaveBackup.utils.AlertUtil;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;
import lombok.Data;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@Data
public class BackupDialogController {
    @FXML private TableView<JSONObject> saveTable;
    @FXML private TableColumn<JSONObject, String> nameColumn;
    @FXML private TableColumn<JSONObject, String> sizeColumn;
    @FXML private TableColumn<JSONObject, String> createdColumn;
    @FXML private TableColumn<JSONObject, Void> operationColumn;

    @FXML private Button prevPageBtn;
    @FXML private Button nextPageBtn;
    @FXML private Label pageInfoLabel;

    private Stage dialogStage;

    //游戏信息
    private GameSaveBackVo game;

    private int pageSize = 10; // 每页显示10条
    private int current = 1; // 当前页码（从1开始）
    private int totalPage = 1; //总页数
    //所有数据集合
    private JSONArray allDataList = new JSONArray();
    //分页数据集合
    private ObservableList<JSONObject> dataList = FXCollections.observableArrayList();


    //初始化
    @FXML
    private void initialize() {
        // 初始化表格列
        nameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<JSONObject, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<JSONObject, String> param) {
                // 直接通过键名从 JSONObject 中获取值
                String fileName = param.getValue().getString("name");
                return new SimpleStringProperty(fileName);
            }
        });
        sizeColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<JSONObject, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<JSONObject, String> param) {
                // 直接通过键名从 JSONObject 中获取值
                BigDecimal size = new BigDecimal(param.getValue().getInteger("size")).divide(new BigDecimal(1024),2, BigDecimal.ROUND_HALF_UP);
                String fileName = size.toString()+"K";
                return new SimpleStringProperty(fileName);
            }
        });
        createdColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<JSONObject, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<JSONObject, String> param) {
                // 直接通过键名从 JSONObject 中获取值
                String fileName = "";
                try {
                    Date time = time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX").parse(param.getValue().getString("created"));
                    fileName = DateUtil.formatDateTime(time);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return new SimpleStringProperty(fileName);
            }
        });
        // 操作列（同步+删除按钮）
        operationColumn.setCellFactory(col -> new TableCell<>() {
            private final Button syncBtn = new Button("同步");
            private final Button deleteBtn = new Button("删除");

            {
                // 按钮样式（与主窗口保持一致）
                syncBtn.setStyle("-fx-background-color: #2196F3; -fx-text-fill: white; -fx-padding: 4 8; -fx-font-size: 12px;");
                deleteBtn.setStyle("-fx-background-color: #f44336; -fx-text-fill: white; -fx-padding: 4 8; -fx-font-size: 12px;");
                syncBtn.setPrefWidth(60);
                deleteBtn.setPrefWidth(60);

                // 同步按钮事件
                syncBtn.setOnAction(e -> {
                    JSONObject selectedSave = getTableView().getItems().get(getIndex());
                    handleSyncSave(selectedSave);
                });

                // 删除按钮事件
                deleteBtn.setOnAction(e -> {
                    JSONObject selectedSave = getTableView().getItems().get(getIndex());
                    handleDeleteSave(selectedSave);
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    // 按钮横向排列
                    HBox hbox = new HBox(5);
                    hbox.getChildren().addAll(syncBtn, deleteBtn);
                    setGraphic(hbox);
                }
            }
        });

    }

    //加载数据
    public void loadDate(){
        dialogStage.setTitle(game.getGameName() + " - 选择云端存档");
        //查询全部
        allDataList = GameSaveBackupService.getBackupFileList(game,1,0);
        if (CollUtil.isEmpty(allDataList)){
            allDataList = new JSONArray();
        }
        //计算总页数
        totalPage = CollUtil.isEmpty(allDataList) ? 1 : (allDataList.size() + pageSize - 1) / pageSize;
        //裁取当前分页数据
        loadCurrentPageData();
    }

    //裁取当前分页数据
    private void loadCurrentPageData(){
        dataList.clear();
        //分页 裁剪
        int startIndex = (current - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, allDataList.size());
        if (startIndex < endIndex && CollUtil.isNotEmpty(allDataList)) {
            allDataList.subList(startIndex, endIndex).stream().forEach(item -> {
                dataList.add((JSONObject) item);
            });
        }
        //渲染
        saveTable.setItems(dataList);
        //更新当前页数
        pageInfoLabel.setText(String.format("第 %d 页 / 共 %d 页（每页 %d 条）", current, totalPage, pageSize));
        //更新上下页按钮是否禁用
        btnDisableChange();
    }



    // 上一页
    @FXML
    private void handlePrevPage() {
        if (current > 1) {
            current--;
            loadCurrentPageData();
        }
    }

    // 下一页
    @FXML
    private void handleNextPage() {
        if (current < getTotalPage()) {
            current++;
            loadCurrentPageData();
        }
    }

    //更新上下页按钮是否禁用
    private void btnDisableChange(){
        nextPageBtn.setDisable(current >= getTotalPage());
        prevPageBtn.setDisable(current <= 1);
    }

    // 同步存档
    private void handleSyncSave(JSONObject fileInfo) {
        String fileName = fileInfo.getString("name");
        boolean confirm = AlertUtil.showConfirmationAlert("确认同步",
                String.format("是否同步存档【%s】到本地？\n同步后会覆盖当前本地存档！", fileName));
        if (confirm) {
            try {
                boolean success = GameSaveBackupService.recovery(game,fileName,true);
                if (success) {
                    AlertUtil.showInfoAlert("成功", "同步成功", "游戏存档已成功同步到本地");
                } else {
                    AlertUtil.showErrorAlert("失败", "同步失败", "无法将存档同步到本地");
                }
            } catch (Exception e) {
                e.printStackTrace();
                AlertUtil.showErrorAlert("错误", "同步过程出错", e.getMessage());
            }
        }
    }

    // 删除云端存档
    private void handleDeleteSave(JSONObject fileInfo) {
        String fileName = fileInfo.getString("name");
        boolean confirm = AlertUtil.showConfirmationAlert("确认删除",
                String.format("是否永久删除云端存档【%s】？\n删除后无法恢复！", fileName));
        if (confirm) {
            try {
                boolean success = GameSaveBackupService.delete(game,fileName);
                //刷新页面
                loadDate();
                if (success) {
                    AlertUtil.showInfoAlert("成功", "删除成功", "");
                } else {
                    AlertUtil.showErrorAlert("失败", "删除失败", "");
                }

            } catch (Exception e) {
                e.printStackTrace();
                AlertUtil.showErrorAlert("错误", "删除过程出错", e.getMessage());
            }
        }

    }
}